﻿using System;
using System.Windows;
using System.Windows.Threading;

using Coding4Fun.FakeCall.Data;

using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace Coding4Fun.FakeCall
{
	public partial class LockScreen : PhoneApplicationPage
	{
		readonly DispatcherTimer _clockTimer;
		readonly DateTime _endTime;

		public LockScreen()
		{
			InitializeComponent();
			PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
			ResetControl();

			var settings = FakeCallSettings.Instance;
			
			_endTime = DateTime.Now.Add(
				new TimeSpan(
				settings.TimeDelay.Hours,
				settings.TimeDelay.Minutes,
				settings.TimeDelay.Seconds));
			
			_clockTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
			_clockTimer.Tick += OnClockTick;
			_clockTimer.Start();
		}

		private void OnClockTick(object sender, EventArgs e)
		{
			lockControl.Settings.LockScreenTime = lockControl.Settings.LockScreenTime.Add(_clockTimer.Interval);

			if (lockControl.IsLocked && _endTime <= DateTime.Now)
			{
				receivingCall.Visibility = Visibility.Visible;
				_clockTimer.Stop();
			}
		}

		private void BackGround_RestartClick(object sender, RoutedEventArgs e)
		{
			Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/SettingPivot.xaml", UriKind.Relative)));
		}

		public void ResetControl()
		{
			receivingCall.Visibility = Visibility.Collapsed;
			receivingCall.StopAllCallActions();
			inProgress.Visibility = Visibility.Collapsed;
			
		}

		private void receivingCall_CallAnswered(object sender, RoutedEventArgs e)
		{
			inProgress.Visibility = Visibility.Visible;
			receivingCall.Visibility = Visibility.Collapsed;
			receivingCall.StopAllCallActions();
		}

		private void call_CallEnded(object sender, RoutedEventArgs e)
		{
			ResetControl();
		}

		protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
		{
			_clockTimer.Stop();
			base.OnBackKeyPress(e);
		}

		protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
		{
			_clockTimer.Stop();
			base.OnNavigatedFrom(e);
		}
	}
}